package persons.web;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import server.IAmServer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Ann Raboschuk
 */
public class PersonsController implements Controller
{
   protected final Log logger = LogFactory.getLog(getClass());

   private IAmServer server;

   public ModelAndView handleRequest(HttpServletRequest request,
         HttpServletResponse response) throws ServletException, IOException
   {
      ModelAndView page = null;
      Map<String, Object> myModel = new HashMap<String, Object>();
      String id = request.getParameter("id");
      if (id != null)
      {
         server.delete(server.getPersonById(Long.valueOf(id)));
         myModel.put("persons", this.server.loadAll());
         page = new ModelAndView(new RedirectView("persons.htm"));
      }
      else
      {
         myModel.put("persons", this.server.loadAll());
         page = new ModelAndView("persons", "model", myModel);
      }
      return page;
   }

   public void setServer(IAmServer server)
   {
      this.server = server;
   }
}
